package com.wangan;

import org.openqa.selenium.Pdf;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.print.PrintOptions;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        // 获取 java 版本
        String version = System.getProperty("java.specification.version");

        // 获取系统类型
        String platform = System.getProperty("os.name", "");
        platform = platform.toLowerCase().contains("window") ? "win" : "linux";

        // 当前程序目录
        String current = System.getProperty("user.dir");

        System.out.println("current:" + current);

        // firefox 运行参数配置
        FirefoxOptions options = new FirefoxOptions();
        // 无头模式
        options.addArguments("--headless");
        // 最大化
        options.addArguments("--start-maximized");

        FirefoxDriver browser = new FirefoxDriver(options);

        Path url = Paths.get(current, "..", "index.html");
        System.out.println("url:" + url.toString());

        // NOTE 要使用 file 协议
        browser.get(String.format("file://%s", url.toString()));

        // 打印设置
        PrintOptions print = new PrintOptions();
        Pdf pdf = browser.print(print);

        // pdf base64 内容
        String content = pdf.getContent();
        // 解码内容
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] buffer = decoder.decode(content);

        try {
            // 将 byte 写入文件
            Path file = Paths.get(String.format("java%s_%s.pdf", version, platform));
            Files.write(file, buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            browser.quit();
        }
    }
}